package com.uchengwang.ui.cm_ui.uu.ui;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.UserConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.ucity.cityBean.UserBeanList;
import com.uchengwang.ui.cm_ui.uu.adapter.AddAdapter;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.PopupUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by U城网 on 2017/6/3.
 * 添加好友界面
 */

public class AddFriendActivity extends BaseWithTitleActivity{
    private LinearLayout add_search;
    private RecyclerView add_rv;
    private AddAdapter addAdapter;
    private PtrClassicFrameLayout refresh;
    private RecyclerAdapterWithHF mAdapter;
    private EditText search_text;
    private int page = 1, totlaPagers;
    private View view;
    private TextView popup_search;//搜索显示
    private PopupUtils popupUtils;
    private boolean isRecomment = true;
    private int findType;//1找人[只可以搜索] 2找同学[有推荐和按条件筛选] 3找社团 4查看关系朋友
    private String year, sameType = "";//筛选条件 入学年份 是否同校 同城

    private int sex = -1;//筛选性别 0=女 1=男

    private int userRole = 1;//搜索的用户角色  普通用户可以获取推荐查询  社团用户不获取推荐直接分页加载
    public static int addIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_friend);
        userRole = getIntent().getIntExtra(BaseConfig.USER_ROLE, 1);
        findType = getIntent().getIntExtra(BaseConfig.TYPE, 1);

        if(userRole == BaseConfig.STUDENT_ROLE){
            setTitle("添加");
        }else {
            setTitle("搜索");
            isRecomment = false;
        }
        EventBus.getDefault().register(this);

        setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UCommonUtil.getUtil().hideSoftInput(AddFriendActivity.this, search_text);
                AddFriendActivity.this.finish();
            }
        });

        initView();

    }

    private void initView(){
        refresh = (PtrClassicFrameLayout) findViewById(R.id.add_refresh);
        add_search = (LinearLayout) findViewById(R.id.add_search);
        add_rv = (RecyclerView) findViewById(R.id.add_rv);

        add_rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        search_text = (EditText) findViewById(R.id.add_search_text);
        search_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (popupUtils != null){
                    popupUtils.dismiss();
                }
                String k = search_text.getText().toString();
                if (TextUtils.isEmpty(k)){
                    return true;
                }
                refresh.setAutoLoadMoreEnable(true);
                refresh.setLoadMoreEnable(true);
                page = 1;
                getFriends(true, search_text.getText().toString());

                return true;
            }
        });
        view = LayoutInflater.from(this).inflate(R.layout.popup_view, null, false);

        search_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString() != null && s.length() > 0) {
                    isRecomment = false;

                    if (view == null){
                        view = LayoutInflater.from(AddFriendActivity.this).inflate(R.layout.popup_view, null, false);
                    }
                    popup_search = (TextView) view.findViewById(R.id.popup_search);
                    popup_search.setText(s.toString());
                    popup_search.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupUtils.dismiss();

                            refresh.setAutoLoadMoreEnable(true);
                            refresh.setLoadMoreEnable(true);

                            page = 1;
                            getFriends(true, search_text.getText().toString());
                        }
                    });
                    if (popupUtils == null || !popupUtils.isShow()) {
                        popupUtils = PopupUtils.getUtils().showView(AddFriendActivity.this, view, false, false, false);
                        popupUtils.showNo(add_search);
                    }
                } else {
                    popupUtils.dismiss();

                    if(userRole == BaseConfig.STUDENT_ROLE){
                        //获取推荐的
//                        refresh.setAutoLoadMoreEnable(false);
//                        refresh.setLoadMoreEnable(false);
                        isRecomment = true;
                    }

                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        switch (findType){
            case 1://找人 只可以搜索


                break;
            case 2://找同学 有推荐和按条件
//                add_search.setVisibility(View.GONE);
//                setRightImage(R.drawable.image_menu, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        PopupUtils.getUtils().selectPerson(AddFriendActivity.this, sex==0, sameType.equals("同城"), year, new PopupUtils.PopupConditionListener() {
//                            @Override
//                            public void onResult(List<String> list) {
//                                if (list != null && list.size() >0){
//                                    String sexType = list.get(0);
//                                    sameType = list.get(1);
//                                    year = list.get(2);
//
//                                    if (sexType.equals("女")){
//                                        sex = 0;
//                                    }else {
//                                        sex = 1;
//                                    }
//
//                                    page =1;
//                                    getFriends(true, "");
//
//                                }
//                            }
//                        }).show(AddFriendActivity.this, getRy());
//
//                    }
//                });
                break;
        }

        initData();
    }

    private void initData(){
        add_rv.setLayoutManager(new LinearLayoutManager(this));
        addAdapter = new AddAdapter(this);
        mAdapter = new RecyclerAdapterWithHF(addAdapter);

        add_rv.setAdapter(mAdapter);

        refresh.setAutoLoadMoreEnable(true);
        refresh.setLoadMoreEnable(true);


        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                refresh.autoRefresh(true);
            }
        }, 150);

        refresh.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                switch (findType){
                    case 1://找人
                        if (refresh.isRefreshing()){
                            refresh.refreshComplete();
                        }
                        search_text.requestFocus();
                        UCommonUtil.getUtil().showSoftInput(AddFriendActivity.this, search_text);
                        break;
                    case 2://找同学
                    case 4://查看关系朋友
//                        getRecommentFriends();
                        page = 1;
                        getFriends(true, search_text.getText().toString());
                        break;
                    case 3://找社团
                        page = 1;
                        getFriends(true, search_text.getText().toString());
                        break;
                }

            }

//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                if (findType==1){
//                    return false;
//                }
//                return true;
//            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                page++;
                if (page <= totlaPagers){
                    //当前请求页大于总页数，不再请求
                    getFriends(false, search_text.getText().toString());
                } else {
                    refresh.loadMoreComplete(false);
                }
            }
        });
    }


    public void onEvent(UserBean b){
        if (b != null){
            List<UserBean> list = addAdapter.getData();
            for (UserBean userBean : list){
                if (userBean.getId() ==b.getId()){
                    userBean.setFollow(b.isFollow());
                    addAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取推荐用户
     * */
//    private void getRecommentFriends(){
//        MapRequest map =new MapRequest();
////        if (UChengApplication.uniId >0){//前期推荐不按学校来
////            map.put(BaseConfig.UNI_ID, UChengApplication.uniId);
////        }
//        HttpManager.newInstance(this).queryCheck(UserConfig.Recomment.method, UserConfig.Recomment.URL, map, new HttpCallBack() {
//            @Override
//            public void onError(int status, String msg) {
//                refresh.refreshComplete();
//                UCommonUtil.getUtil().hideSoftInput(AddFriendActivity.this, search_text);
//                Log.d("jjf", "status="+status+"=msg="+msg);
//            }
//
//            @Override
//            public void onResp(int status, String msg, String data) {
//                Log.d("jjf", "status="+status+"=msg="+msg);
//                UCommonUtil.getUtil().hideSoftInput(AddFriendActivity.this, search_text);
//
//                refresh.refreshComplete();
//
//                if (status != 0){
//                    addAdapter.getData().clear();
//                    addAdapter.notifyDataSetChanged();
//                    return;
//                }
//                if (!TextUtils.isEmpty(data) && !data.equals("[]")){
//                    List<UserBean> listBean = JsonUtils.getManager().parseList(data, UserBean.class);
//                    if (listBean != null && listBean.size() >0){
//                        addAdapter.setData(listBean);
//
//                    }
//                }
//            }
//        });
//    }

    /**
     * 获取好友
     * @param key 搜索关键词
     * */
    private void getFriends(final boolean isRefresh, String key){
        String url = "";
        switch (findType){
            case 1://找人
                url = UserConfig.ChangeInfo.URL;
                break;
            case 2://找同学
                url = UserConfig.ChangeInfo.URL;
                break;
            case 3://找社团
                url = UserConfig.ChangeInfo.URL;
                break;
            case 4://查看关系朋友
                url = "/user/intersection";

                break;
        }

        MapRequest map =new MapRequest();
        if (!TextUtils.isEmpty(key)){
            map.put(BaseConfig.KEY_WORD, key);
            url = UserConfig.ChangeInfo.URL;
        }else {
            if (findType != 4){
                map.put(BaseConfig.ORDERBY, BaseConfig.ID);
                map.put(BaseConfig.ORDER, BaseConfig.DESC);
                map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);
                map.put(BaseConfig.ROLE, userRole);
            }
        }

//        map.put(BaseConfig.ORDERBY, BaseConfig.ID);
//        map.put(BaseConfig.ORDER, BaseConfig.DESC);
//        map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);

//        map.put(BaseConfig.ROLE, userRole);
        if (sex >=0){
            map.put(BaseConfig.SEX, sex);
        }

        if (!TextUtils.isEmpty(year)){
            map.put(BaseConfig.YEAR, year);
        }
        if (sameType.equals("本校")){
            map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);
        }

        map.put(BaseConfig.PAGE, page);
        map.put(BaseConfig.PERPAGE, 10);

        HttpManager.newInstance(this).query(UserConfig.ChangeInfo.method_check, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                if (isRefresh){
                    refresh.refreshComplete();
                }else {
                    refresh.loadMoreComplete(true);
                }
                UCommonUtil.getUtil().hideSoftInput(AddFriendActivity.this, search_text);
                Log.d("jjf", "status="+status+"=msg="+msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                UCommonUtil.getUtil().hideSoftInput(AddFriendActivity.this, search_text);
                if (isRefresh){
                    refresh.refreshComplete();
                }else {
                    refresh.loadMoreComplete(true);
                }

                if (status != 0){
                    addAdapter.getData().clear();
                    addAdapter.notifyDataSetChanged();
                    UCommonUtil.getUtil().showToast(AddFriendActivity.this, msg);
                    return;
                }
                if (!TextUtils.isEmpty(data) && !data.equals("[]")){
                    UserBeanList listBean = JsonUtils.getManager().stringToBean(data, UserBeanList.class);
                    List<UserBean> list = listBean.getData();
                    totlaPagers = listBean.getTotalPage();

                    if (list != null && list.size() >0){
                        if (isRefresh){
                            addAdapter.setData(list);
                        }else {
                            addAdapter.getData().addAll(list);
                            addAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
    }



}
